using System;
using Volo.Abp.Domain.Entities.Auditing;

namespace CKY.AgentPlatform.ModelConfigs;

/// <summary>
/// AI模型提供商枚举
/// </summary>
public enum ModelProvider
{
    /// <summary>
    /// OpenAI
    /// </summary>
    OpenAI = 0,
    
    /// <summary>
    /// Anthropic Claude
    /// </summary>
    Anthropic = 1,
    
    /// <summary>
    /// Google Gemini
    /// </summary>
    Google = 2,
    
    /// <summary>
    /// 百度文心一言
    /// </summary>
    Baidu = 3,
    
    /// <summary>
    /// 阿里云通义千问
    /// </summary>
    Alibaba = 4,
    
    /// <summary>
    /// 智谱AI
    /// </summary>
    ZhipuAI = 5,
    
    /// <summary>
    /// 月之暗面
    /// </summary>
    Moonshot = 6,

    /// <summary>
    /// Azure OpenAI
    /// </summary>
    AzureOpenAI = 7,

    /// <summary>
    /// Ollama
    /// </summary>
    Ollama = 8,

    /// <summary>
    /// 自定义模型
    /// </summary>
    Custom = 99
}

/// <summary>
/// 模型配置实体 - AI模型配置管理
/// </summary>
public class ModelConfig : AuditedAggregateRoot<Guid>
{
    /// <summary>
    /// 配置名称
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// 配置描述
    /// </summary>
    public string Description { get; set; }

    /// <summary>
    /// 模型提供商
    /// </summary>
    public ModelProvider Provider { get; set; }

    /// <summary>
    /// 模型名称
    /// </summary>
    public string Model { get; set; }

    /// <summary>
    /// API密钥
    /// </summary>
    public string ApiKey { get; set; }

    /// <summary>
    /// API基础URL
    /// </summary>
    public string ApiBaseUrl { get; set; }

    /// <summary>
    /// 最大令牌数
    /// </summary>
    public int MaxTokens { get; set; }

    /// <summary>
    /// 温度值（0-2）
    /// </summary>
    public double Temperature { get; set; }

    /// <summary>
    /// Top P值（0-1）
    /// </summary>
    public double TopP { get; set; }

    /// <summary>
    /// 频率惩罚系数
    /// </summary>
    public double FrequencyPenalty { get; set; }

    /// <summary>
    /// 存在惩罚系数
    /// </summary>
    public double PresencePenalty { get; set; }

    /// <summary>
    /// 是否激活
    /// </summary>
    public bool IsActive { get; set; }

    /// <summary>
    /// 请求超时时间（秒）
    /// </summary>
    public int TimeoutSeconds { get; set; }

    /// <summary>
    /// 最大重试次数
    /// </summary>
    public int MaxRetries { get; set; }

    /// <summary>
    /// 每分钟最大请求数
    /// </summary>
    public int RateLimitPerMinute { get; set; }

    /// <summary>
    /// 代理设置
    /// </summary>
    public string ProxySettings { get; set; }

    /// <summary>
    /// 自定义参数（JSON格式）
    /// </summary>
    public string CustomParameters { get; set; }

    /// <summary>
    /// 额外配置（Dictionary格式）
    /// </summary>
    public Dictionary<string, object> AdditionalConfig { get; set; }

    /// <summary>
    /// 使用次数统计
    /// </summary>
    public int UsageCount { get; set; }

    /// <summary>
    /// 成功次数统计
    /// </summary>
    public int SuccessCount { get; set; }

    /// <summary>
    /// 失败次数统计
    /// </summary>
    public int FailureCount { get; set; }

    /// <summary>
    /// 总Token使用量
    /// </summary>
    public long TotalTokensUsed { get; set; }

    /// <summary>
    /// 总响应时间（毫秒）
    /// </summary>
    public long TotalResponseTimeMs { get; set; }

    /// <summary>
    /// 最后使用时间
    /// </summary>
    public DateTime? LastUsedAt { get; set; }

    protected ModelConfig()
    {
        // EF Core requires parameterless constructor
    }

    /// <summary>
    /// 创建新的模型配置实例
    /// </summary>
    /// <param name="id">配置ID</param>
    /// <param name="name">配置名称</param>
    /// <param name="description">配置描述</param>
    /// <param name="provider">模型提供商</param>
    /// <param name="model">模型名称</param>
    /// <param name="apiKey">API密钥</param>
    public ModelConfig(
        Guid id,
        string name,
        string description,
        ModelProvider provider,
        string model,
        string apiKey) : base(id)
    {
        Name = name;
        Description = description;
        Provider = provider;
        Model = model;
        ApiKey = apiKey;
        MaxTokens = 4096;
        Temperature = 0.7;
        TopP = 1.0;
        FrequencyPenalty = 0;
        PresencePenalty = 0;
        IsActive = true;
        TimeoutSeconds = 30;
        MaxRetries = 3;
        RateLimitPerMinute = 60;
        ProxySettings = "";
        CustomParameters = "{}";
        AdditionalConfig = new Dictionary<string, object>();
        UsageCount = 0;
        SuccessCount = 0;
        FailureCount = 0;
        TotalTokensUsed = 0;
        TotalResponseTimeMs = 0;
    }

    /// <summary>
    /// 更新使用统计
    /// </summary>
    /// <param name="tokensUsed">使用的Token数量</param>
    /// <param name="isSuccess">是否成功</param>
    public void UpdateUsageStats(long tokensUsed, bool isSuccess)
    {
        UsageCount++;
        TotalTokensUsed += tokensUsed;
        LastUsedAt = DateTime.UtcNow;

        if (isSuccess)
        {
            SuccessCount++;
        }
        else
        {
            FailureCount++;
        }
    }

    /// <summary>
    /// 获取成功率
    /// </summary>
    /// <returns>成功率（0-1）</returns>
    public double GetSuccessRate()
    {
        if (UsageCount == 0)
            return 1.0;

        return (double)SuccessCount / UsageCount;
    }

    /// <summary>
    /// 获取平均Token使用量
    /// </summary>
    /// <returns>平均Token使用量</returns>
    public double GetAverageTokens()
    {
        if (SuccessCount == 0)
            return 0;

        return (double)TotalTokensUsed / SuccessCount;
    }

    /// <summary>
    /// 检查配置是否有效
    /// </summary>
    /// <returns>是否有效</returns>
    public bool IsValid()
    {
        return !string.IsNullOrWhiteSpace(ApiKey) &&
               !string.IsNullOrWhiteSpace(Model) &&
               MaxTokens > 0 &&
               Temperature >= 0 && Temperature <= 2 &&
               TopP >= 0 && TopP <= 1 &&
               TimeoutSeconds > 0;
    }

    /// <summary>
    /// 获取提供商的默认API基础URL
    /// </summary>
    /// <returns>默认API基础URL</returns>
    public string GetDefaultApiBaseUrl()
    {
        return Provider switch
        {
            ModelProvider.OpenAI => "https://api.openai.com/v1",
            ModelProvider.Anthropic => "https://api.anthropic.com",
            ModelProvider.Google => "https://generativelanguage.googleapis.com/v1beta",
            ModelProvider.Baidu => "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat",
            ModelProvider.Alibaba => "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation",
            ModelProvider.ZhipuAI => "https://open.bigmodel.cn/api/paas/v4",
            ModelProvider.Moonshot => "https://api.moonshot.cn/v1",
            ModelProvider.AzureOpenAI => "https://{resource}.openai.azure.com/openai/deployments/{deployment}/chat/completions?api-version=2023-12-01-preview",
            ModelProvider.Ollama => "http://localhost:11434/api/generate",
            _ => ""
        };
    }

    /// <summary>
    /// 重置统计信息
    /// </summary>
    public void ResetStats()
    {
        UsageCount = 0;
        SuccessCount = 0;
        FailureCount = 0;
        TotalTokensUsed = 0;
        LastUsedAt = null;
    }

    /// <summary>
    /// 获取配置摘要信息
    /// </summary>
    /// <returns>摘要信息</returns>
    public string GetSummary()
    {
        return $"{Provider} - {Model} (MaxTokens: {MaxTokens}, Temperature: {Temperature})";
    }

    /// <summary>
    /// 激活配置
    /// </summary>
    public void Activate()
    {
        IsActive = true;
    }

    /// <summary>
    /// 停用配置
    /// </summary>
    public void Deactivate()
    {
        IsActive = false;
    }
}